<?php
namespace Api\Controller;
use Api\Controller\CommonController;
use JPush\Model as M;
use JPush\JPushClient;
use JPush\Exception\APIRequestException;
use JPush\Exception\APIConnectionException;
class CodePayController extends CommonController {
	const CHANNEL = 'A0001';
	const GET_CODE = 306;
	const REGIST_CODE = 301;
	const BIND_CARD = 304;
	const SET_PASS = 302;
	const RESET_PASS = 303;
	const UNBIND_CARD = 305;
	const SEARCH_CODE = 309;
	const EDIT_CODE = 310;
	const CHECK_PASS = 311;
	const SEARCH_CARD = 312;
	const SET_CARD = 313;
	const SEARCH_ORDER = 315;
	
	const NEED_CHECK_PASS = 307;
	const PUSH_ORDER = 308;
	
	const GET_PHONECODE = 316;
	const CHECK_PHONECODE = 317;
	
	const CHECK_OTHERPASS = 319;
	const CHECK_ISNEEDPASS=320;
	
	
	public function _initialize(){
		parent::_initialize();
		 
		//登录验证
		if(!(ACTION_NAME=="acceptData" || ACTION_NAME=="test" || ACTION_NAME=="getShiming" || ACTION_NAME=="realnameVertify" || ACTION_NAME=="pushData")){
			$this->_checkLogin();
		}
		
	}
	
	public function test(){
		//$phone = '15989246851';
		$phone = '18680484938';
		
		$user = M('User')->where(array('phone'=>$phone))->find();
		echo $user['accessToken'];
		$msgarray = array('status'=>1,'info'=>"推送成功");
			$msg = json_encode($msgarray);
			$title = "实名认证校验";
			 vendor('JPush/autoload');//JPushClient   notification  APIRequestException APIConnectionException
			//$client = new JPushClient('0335dd3eb505909bdc492d06', 'f9f8e4b165b9448fc0fd0539');   //测试key
			  $client = new JPushClient('161f1017deaf5dc1cba3e83d', 'bb3a91fe849af6cb1d754db9');   //生产key
			try {
					$result = $client->push()
						->setPlatform( M\all )
						//->setAudience( M\all)
						->setAudience(M\audience(M\alias(array($user['accessToken']))))
						//->setNotification( 
						//    M\notification($msg, 
						//    M\ios($title, null, null, null, $msgarray, null),
						//    M\android($title, null, null, $msgarray)
						//))
						->setMessage(M\message($msg, $title, 'array', $msgarray))
						//->printJSON()
						->send();
				
				
						
				var_dump($result);
				
			} catch (APIRequestException $e) {
				echo "false";exit;
				return false;
			} catch (APIConnectionException $e) {
				echo "false";exit;
				return false;
			}
			echo "ok";
			exit;
		
		
		$this->_sendMsgToUser('18664699093',json_encode(array('status'=>1)),"test");
		exit;
		set_time_limit(0);
		//ob_implicit_flush();

		$address = '0.0.0.0';
		$port = 8083;
		//创建端口
		if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
			echo "socket_create() failed :reason:" . socket_strerror(socket_last_error()) . "\n";
		}

		//绑定
		if (socket_bind($sock, $address, $port) === false) {
			echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
		}

		//监听
		if (socket_listen($sock, 5) === false) {
			echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
		}

		do {
			//得到一个链接
			if (($msgsock = socket_accept($sock)) === false) {
				echo "socket_accepty() failed :reason:".socket_strerror(socket_last_error($sock)) . "\n";
				break;
			}
			//welcome  发送到客户端
			$msg = "<font color='red'>server send:welcome</font><br/>";
			socket_write($msgsock, $msg, strlen($msg));
			echo 'read client message\n';
			$buf = socket_read($msgsock, 1024);
			$talkback = "received message:$buf\n";
			echo $talkback;
			if (false === socket_write($msgsock, $talkback, strlen($talkback))) {
				echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."\n";
			} else {
				echo 'send success';
			}
			socket_close($msgsock);
		} while(true);
		//关闭socket
		socket_close($sock);
	}
	
	/**
     * 推送
     */
	 
    private function _sendMsgToUser($chan_user,$msg, $title, $extras = array()) {
		$msgjson = json_decode($msg);
		$msgarray = json_decode($msg,true);
		$order_id = $msgjson->order_id;
        vendor('JPush/autoload');//JPushClient   notification  APIRequestException APIConnectionException
        //$client = new JPushClient('0335dd3eb505909bdc492d06', 'f9f8e4b165b9448fc0fd0539');   //测试key
		  $client = new JPushClient('161f1017deaf5dc1cba3e83d', 'bb3a91fe849af6cb1d754db9');   //生产key
        try {
				$result = $client->push()
                    ->setPlatform( M\all )
                    //->setAudience( M\all)
					->setAudience(M\audience(M\alias(array($chan_user))))
                    //->setNotification( 
                    //    M\notification($msg, 
                    //    M\ios($title, null, null, null, $msgarray, null),
                    //    M\android($title, null, null, $msgarray)
                    //))
                    ->setMessage(M\message($msg, $title, 'array', $msgarray))
                    //->printJSON()
                    ->send();
            return $result;
        } catch (APIRequestException $e) {
            return false;
        } catch (APIConnectionException $e) {
            return false;
        }
    }
	
	
	
	
	
	//自定义函数用于获取消息
	function receive_message($address,$port,$nbsecondsidle=5)
	{
	  //创建socket
	 /* $socket=stream_socket_server('tcp://'.$address.':'.$port, $errno, $errstr);
	  if(!$socket)
	  {
		echo "$errstr ($errno)";
		exit;
	  }
	  else
	  {
		//如果创建成功则接受socket连接并获取信息
		while($conn=@stream_socket_accept($socket,$nbsecondsidle))
		{
		  $message=read($conn,1024);
		  fclose ($conn);
		  $message = json_decode($message);
		  $mobile = $message->chan_user;
		  $msg = json_encode(array('result'=>1,'order_id'=>$message->order_id));
		  $title = "needCheckPass";
		  $this->_sendMsgToUser($mobile,$msg,$title);
		  
		}
		fclose($socket);
	  }
	  */
//ignore_user_abort(1);
// 设置错误处理
error_reporting(E_ALL);
// 设置运行时间
set_time_limit(0);
// 起用缓冲
ob_implicit_flush();
	  if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
			echo "socket_create() failed :reason:" . socket_strerror(socket_last_error()) . "\n";
			exit;
		}

		//绑定
		if (socket_bind($sock, $address, $port) === false) {
			echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
			exit;
		}

		//监听
		if (socket_listen($sock, 5) === false) {
			echo "socket_bind() failed :reason:" . socket_strerror(socket_last_error($sock)) . "\n";
			exit;
		}

		do {
			//得到一个链接
			if (($msgsock = socket_accept($sock)) === false) {
				echo "socket_accepty() failed :reason:".socket_strerror(socket_last_error($sock)) . "\n";
				break;
			}
			$msg = iconv("GBK", "UTF-8", socket_read($msgsock, 8192));
			
			file_put_contents("payLog/pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msg."|receive",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
			
			$msg = json_decode($msg);
			
			if($msg->txn_id==self::NEED_CHECK_PASS){
				$type="needCheckPass";
			}elseif($msg->txn_id==self::PUSH_ORDER){
				$type="pushOrder";
			}
			if($type=="needCheckPass"){
				$msgtozj = array(
				'txn_id'=> $msg->txn_id,
				'channel'=> $msg->channel,
				'chan_user'=>$msg->chan_user,
				'systrace'=>$msg->systrace,
				'rc'=>'00',
				'rc_detail'=>'成功',
				'txn_time'=>date("His"),
				'txn_date'=>date("Ymd"),
				'order_id'=>$msg->order_id
				);
			}elseif($type=="pushOrder"){
				$msgtozj = array(
				'txn_id'=> $msg->txn_id,
				'channel'=> $msg->channel,
				'chan_user'=>$msg->chan_user,
				'systrace'=>$msg->systrace,
				'rc'=>'00',
				'rc_detail'=>'成功',
				'order_id'=>$msg->order_id
				);
			}
			$msgtozj = $this->getdata($msgtozj);
			
			
			
			/*if($type=="needCheckPass"){
					$title = "needCheckPass";
					$msgtoapp = json_encode(array('type'=>$title,'result'=>1,'order_id'=>$msg->order_id,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
				}elseif($type=="pushOrder"){
					$title = "pushOrder";
					if($msg->rc == "00"){
						$user = M('User')->where(array('phone'=>$msg->chan_user))->find();
						$codepay=array(
							'userID'=>$user['userID'],
							'systrace'=>$msg->systrace,
							'order_time'=>$msg->order_time,
							'payed_time'=>$msg->payed_time,
							'order_id'=>$msg->order_id,
							'host_order_id'=>$msg->host_order_id,
							'mid'=>$msg->mid,
							'goods'=>$msg->goods,
							'order_status'=>$msg->order_status
						);
						M('CodePay')->add($codepay);
						$msgtoapp = json_encode(array('type'=>$title,'result'=>1,'order_id'=>$msg->order_id,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
					}else{
						$msgtoapp = json_encode(array('type'=>$title,'result'=>0,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
					}
					
				}
				file_put_contents("payLog/codePay_".date("Ymd").".txt", json_encode($msgtoapp,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
				$result = $this->_sendMsgToUser($user['accessToken'],$msgtoapp,$title);
				$msgtoapp = json_decode($msgtoapp,true);
				$msgtoapp['pushresult']= $result;
				$msgtoapp['user']= $msg->chan_user;
				$msgtoapp = json_encode($msgtoapp);
				
			if (false === socket_write($msgsock, $msgtoapp, strlen($msgtoapp))) {*/
			
			
			
			if (false === socket_write($msgsock, $msgtozj, strlen($msgtozj))) {
				echo "socket_write() failed reason:" . socket_strerror(socket_last_error($sock)) ."\n";
			} else {
				//$user = M('User')->where(array('phone'=>'18680484938'))->find();
				$user = M('User')->where(array('phone'=>$msg->chan_user))->find();
				if($type=="needCheckPass"){
					$title = "needCheckPass";
					$msgtoapp = json_encode(array('type'=>$title,'result'=>1,'order_id'=>$msg->order_id,'mid'=>$msg->mid,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
				}elseif($type=="pushOrder"){
					$title = "pushOrder";
					if($msg->rc == "00"){
						try{
							if(isset($msg->goods) && $msg->goods){
							$goods = $msg->goods;
							}else{
								$goods=null;
							}
							
							$codepay=array(
								'userID'=>$user['userID'],
								'systrace'=>$msg->systrace,
								'order_time'=>$msg->order_time,
								'payed_time'=>$msg->payed_time,
								'order_id'=>$msg->order_id,
								'host_order_id'=>$msg->host_order_id,
								'mid'=>$msg->mid,
								'goods'=>$goods,
								'order_status'=>$msg->order_status
							);
							M('CodePay')->add($codepay);
							$msgtoapp = json_encode(array('type'=>$title,'result'=>1,'order_id'=>$msg->order_id,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo,'order_status'=>$msg->order_status));
						}
						catch(Exception $e){
							file_put_contents("payLog/pushorder_".date("Ymd").".txt", json_encode(json_encode($e)."-----------------------",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
						}
					}else{
						$msgtoapp = json_encode(array('type'=>$title,'result'=>0,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
					}
					
				}
				file_put_contents("payLog/pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msgtoapp."|beforesend",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
				$result = $this->_sendMsgToUser($user['accessToken'],$msgtoapp,$title);
				file_put_contents("payLog/pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msgtoapp."|aftersend",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
				echo 'send success';
			}
			socket_close($msgsock);
		} while(true);
		//关闭socket
		socket_close($sock);
	  
	}
	
	public function pushData(){
		$msg = $_POST['data'];
		//file_put_contents("pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msg."|receive",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		$msg = json_decode($msg);
			
		if($msg->txn_id==self::NEED_CHECK_PASS){
			$type="needCheckPass";
		}elseif($msg->txn_id==self::PUSH_ORDER){
			$type="pushOrder";
		}
		$user = M('User')->where(array('phone'=>$msg->chan_user))->find();
		if($type=="needCheckPass"){
			$title = "needCheckPass";
			$msgtoapp = json_encode(array('type'=>$title,'result'=>1,'order_id'=>$msg->order_id,'mid'=>$msg->mid,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
		}elseif($type=="pushOrder"){
			$title = "pushOrder";
			if($msg->rc == "00"){
				try{
					if(isset($msg->goods) && $msg->goods){
					$goods = $msg->goods;
					}else{
						$goods=null;
					}
					
					$codepay=array(
						'userID'=>$user['userID'],
						'systrace'=>$msg->systrace,
						'order_time'=>$msg->order_time,
						'payed_time'=>$msg->payed_time,
						'order_id'=>$msg->order_id,
						'host_order_id'=>$msg->host_order_id,
						'mid'=>$msg->mid,
						'goods'=>$goods,
						'order_status'=>$msg->order_status
					);
					M('CodePay')->add($codepay);
					$msgtoapp = json_encode(array('type'=>$title,'result'=>1,'order_id'=>$msg->order_id,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo,'order_status'=>$msg->order_status));
				}
				catch(Exception $e){
					file_put_contents("payLog/pushorder_".date("Ymd").".txt", json_encode(json_encode($e)."-----------------------",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
				}
			}else{
				$msgtoapp = json_encode(array('type'=>$title,'result'=>0,'rc'=>$msg->rc,'info'=>$msg->rc_detail,'memo'=>$msg->memo));
			}
			
		}
		//file_put_contents("payLog/pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msgtoapp."|beforesend",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		$result = $this->_sendMsgToUser($user['accessToken'],$msgtoapp,$title);
		//file_put_contents("payLog/pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msgtoapp."|aftersend",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		echo 'send success';
		//file_put_contents("pushlog_".date("Ymd").".txt", json_encode(date('Y-m-d H:i:s')."|".$msg."|receive",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		
	}
	
	public function acceptData(){
		$this->receive_message('0.0.0.0',8083);
	}
	
	public function checkIsneedpass(){
		$user = $this->user;
		
		$param=array(
				'order_id'=>$_POST['order_id'],
    			"mid"=>$_POST['mid']
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::CHECK_ISNEEDPASS,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace),
			'order_id'=>$param['order_id'],
			'mid'=>$param['mid']
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		
		if($result->rc == "00") {
			$this->_returnJson(array("result"=>1));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
	}
	
	
	/**
	 *  扫码注册
	 */
	 public function registCode(){
		 
		$user = $this->user;
		//$user['uid'] =  5385;
		
		$shiminguser = M('User')->where(array('userID'=>$user['uid']))->find();
		if(!$shiminguser['realname']) $this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证","errorMsg"=>'接口错误',"code"=>"160") ); //实名认证开放
		
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		if($usermodel['regist_code']==1) return true;
		
		//$user['uid'] = 3169;
		//$user['mobileNum'] = '13600459658';
		
		//$data = "test";
		//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::REGIST_CODE,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );

		
		$result = json_decode($result);
		if($result->rc == "Q1") {
			$this->_returnJson(array("result"=>0,"info"=>"已注册扫码","errorMsg"=>'接口错误',"code"=>"119") );
		}
		//保存注册状态
		if($result->rc == "00"){
			$userdata = array('userID'=>$user['uid'],'regist_code'=>1);
			D("User")->updateUser($userdata);
			//$this->_returnJson(array("result"=>1,"info"=>$result));
			return true; 
		}
			
		
    }
	
	/**
	 *  绑定卡号
	 */
	 public function bindCard(){
		 $user = $this->user;
		 //M('UserCard')->where(array('userID'=>$user['uid']))->find()
		 
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if(!$usermodel['realname']){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证才能使用本功能！","code"=>"172") );
		} 
		 
		 $haveregist = $this->registCode();
		 if(!$haveregist){
			 $this->_returnJson(array("result"=>0,"info"=>"请先注册扫码","errorMsg"=>'接口错误',"code"=>"153") );
		 }
		 $user_bank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			if($user_bank){
				$cardphone = $user_bank['cardphone'];
			}else{
				$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
			}
		 $param=array(
    			"pan"=>I("post.pan"),
				"mobile"=>$_POST['mobile'],
    			"password"=>$_POST['password'],
				'verify_code'=>$_POST['verify_code'],
				'teller'=>$cardphone
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		$memo = isset($_POST['memo'])?$_POST['memo']:null;
		
		//绑卡是否需要先执行开通扫码
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		if($usermodel['regist_code']!=1) $this->_returnJson(array("result"=>0,"info"=>"请先注册扫码","errorMsg"=>'接口错误',"code"=>"153") );
		
		
		
		/*$user['uid'] = 5385;
		$user['mobileNum'] = '15989246851';
		$param=array(
    			"pan"=>'6660718400000000125',
    			"password"=>md5('000000')
    	);*/
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		if($memo){
			$data=array(
    		'txn_id'=>self::BIND_CARD,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'card_type'=>1,
			'pan'=>$param['pan'],
			'mobile'=>$param['mobile'],
			'verify_code'=>$param['verify_code'],
			'systrace'=>sprintf("%06d", $systrace),
			'pin_data'=>$param['password'],
			'memo'=>$memo,
			'teller'=>$param['teller']
			);
		}else{
			$data=array(
    		'txn_id'=>self::BIND_CARD,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'card_type'=>1,
			'pan'=>$param['pan'],
			'mobile'=>$param['mobile'],
			'verify_code'=>$param['verify_code'],
			'systrace'=>sprintf("%06d", $systrace),
			'pin_data'=>$param['password'],
			'teller'=>$param['teller']
			);
		}
		

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);

    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		$result = json_decode($result);
		
		
		if($result->rc == "00") {
			if($memo){
				$paypassuser = M('User')->where(array('userID'=>$user['uid']))->find();
				$paypassuser['pay_password'] = null;
				M('User')->save($paypassuser);
			}
			$userCards = M("UserCard")->where(array('userID'=>$user['uid'],'oldornew'=>1))->select();
			foreach($userCards AS $key=>$value){
				$usercarddata['cardID']=$value['cardID'];
				$usercarddata['is_default']=0;
				M("UserCard")->save($usercarddata);
			}
			if($userCard = M("UserCard")->where(array('userID'=>$user['uid'],'cardNum'=>$param['pan'],'oldornew'=>1))->find()){
				D("UserCard")->updateCardNew($userCard['cardID'],$user['uid'],$param['pan'],$param['password']);
			}else{
				D("UserCard")->addCardNew($user['uid'],$param['pan'],$param['password']);
			}
			
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		} else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
		
		
    }
	
	
	
	/**
	 *  获取串码
	 */
	public function getCode(){
		//判断是否注册是否绑卡，待开发，否则进行跳转进行相关操作
		$user = $this->user;
		
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if((!$usermodel['realname']) || (!$usermodel['realname'] && !$usercardmodel)){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证、绑定汇通卡才能使用本功能！","code"=>"168") );
		}                             //实名认证开放
		if(!$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡才能使用本功能！","code"=>"169") );
		}
		
		//$user['uid'] = 5385;
		//$user['mobileNum'] = '15989246851';
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		if($usermodel['regist_code']!=1) $this->_returnJson(array("result"=>0,"info"=>"请先注册扫码","errorMsg"=>'接口错误',"code"=>"150") );
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		
		
		
		if(!$usermodel['realname'] && !$usermodel['pay_password'] && !$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请实名认证、绑定汇通卡和设置支付密码","code"=>"163") );
		}                             //实名认证开放
		if($usermodel['realname'] && !$usermodel['pay_password'] && !$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡和设置支付密码","code"=>"164") );
		}
		if($usermodel['realname'] && !$usermodel['pay_password'] && $usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先设置支付密码","code"=>"165") );
		}
		
		if(!$usercardmodel)$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡","code"=>"167") );
		
		
		//if(!$userdata['pay_password']) $this->_returnJson(array("result"=>0,"info"=>"请先设置支付密码","errorMsg"=>'接口错误',"code"=>"161") );
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::GET_CODE,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		if($result->rc == "00") {
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,'barcode'=>$result->barcode,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    	
    }
	
	public function checkPaypass(){
		$user = $this->user;
		$paypassuser = M('User')->where(array('userID'=>$user['uid']))->find();
		if($paypassuser['pay_password']) {
			$this->_returnJson(array("result"=>1,"info"=>"已经设置过支付密码，请修改支付密码","code"=>"161") );
		} else {
			$this->_returnJson(array("result"=>1,"info"=>"尚未设置支付密码","code"=>"166") );
		}
			
		
	} 
	
	/**
	 *  设置支付密码
	 */
	public function setPass(){
		$user = $this->user;
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if((!$usermodel['realname']) || (!$usermodel['realname'] && !$usercardmodel)){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证、绑定汇通卡才能使用本功能！","code"=>"168") );
		}                             //实名认证开放
		if(!$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡才能使用本功能！","code"=>"169") );
		}
		
		$haveregist = $this->registCode();
		 if(!$haveregist){
			 $this->_returnJson(array("result"=>0,"info"=>"请先注册扫码","errorMsg"=>'接口错误',"code"=>"153") );
		 }
		 
		 $paypassuser = M('User')->where(array('userID'=>$user['uid']))->find();
		if($paypassuser['pay_password']) $this->_returnJson(array("result"=>0,"info"=>"已经设置过支付密码，请修改支付密码","code"=>"161") );
		$user_bank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			if($user_bank){
				$cardphone = $user_bank['cardphone'];
			}else{
				$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
			}
		$param=array(
			'verify_code'=>$_POST['verify_code'],
    			"password"=>$_POST['password'],
				'mobile'=>$cardphone
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::SET_PASS,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'pin_data'=>$param['password'],
			'verify_code'=>$param['verify_code'],
			'mobile'=>$param['mobile'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
    	if($result->rc == "00") {
			$userdata = array('userID'=>$user['uid'],'pay_password'=>$param['password']);
			D("User")->updateUser($userdata);
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	/**
	 *  修改支付密码
	 */
	public function resetPass(){
		
		$user = $this->user;
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if((!$usermodel['realname']) || (!$usermodel['realname'] && !$usercardmodel)){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证、绑定汇通卡才能使用本功能！","code"=>"168") );
		}                             //实名认证开放
		if(!$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡才能使用本功能！","code"=>"169") );
		}
		
		$user_bank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			if($user_bank){
				$cardphone = $user_bank['cardphone'];
			}else{
				$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
			}
		
		$param=array(
				'verify_code'=>$_POST['verify_code'],
    			"password"=>$_POST['password'],
				"password_old"=>$_POST['password_old'],
				'mobile'=>$cardphone
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::RESET_PASS,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'pin_data'=>$param['password'],
			'pin_data_old'=>$param['password_old'],
			'verify_code'=>$param['verify_code'],
			'mobile'=>$param['mobile'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
    	$result = json_decode($result);
    	if($result->rc == "00") {
			$userdata = array('userID'=>$user['uid'],'pay_password'=>$param['password']);
			D("User")->updateUser($userdata);
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	
	/**
	 *  卡号解绑
	 */
	public function unbindCard(){
		
		$param=array(
    			"pan"=>I("post.pan"),
				"pin_data"=>I("post.pin_data")
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		$user = $this->user;
		
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::UNBIND_CARD,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'pan'=>$param['pan'],
			'pin_data'=>$param['pin_data'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		
		
    	$result = json_decode($result);
		
		//$this->_returnJson(array("result"=>0,"info"=>$result->rc));
		
    	if($result->rc == "00") {
			D("UserCard")->unbindCard($user['uid'],$param['pan']);
			//$uc = array('userID'=>$user['uid'],'cardNum'=>$param['pan'],'isOn'=>0);
			//$test = M("UserCard")->save($uc);
			
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	/**
	 *  扫码参数查询
	 */
	 public function searchCode(){
		$user = $this->user;
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::SEARCH_CODE,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		
		if($result->rc == "00") {
			$userdata = array('userID'=>$user['uid'],'regist_code'=>$result->status,'pin_tag'=>$result->pin_tag);
			D("User")->updateUser($userdata);
			$this->_returnJson(array("result"=>1,"status"=>$result->status,"pin_tag"=>$result->pin_tag,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	/**
	 *  扫码参数修改
	 */
	 public function editCode(){
		$user = $this->user;
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if((!$usermodel['realname']) || (!$usermodel['realname'] && !$usercardmodel)){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证、绑定汇通卡才能使用本功能！","code"=>"168") );
		}                             //实名认证开放
		if(!$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡才能使用本功能！","code"=>"169") );
		}
		
		$param=array(
    			"status"=>I("post.status"),
				"pin_tag"=>I("post.pin_tag")
    	);
    	//if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::EDIT_CODE,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'status'=>$param['status'],
			'pin_tag'=>$param['pin_tag'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		
		if($result->rc == "00") {
			$userdata = array('userID'=>$user['uid'],'regist_code'=>$result->status,'pin_tag'=>$result->pin_tag);
			
			M("User")->save($userdata);
			
			$this->_returnJson(array("result"=>1,"status"=>$result->status,"pin_tag"=>$result->pin_tag,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	/**
	 *  验密
	 */
	 public function checkPass(){
		 $param=array(
    			"order_id"=>I("post.order_id"),
				"mid"=>I("post.mid"),
				"pin_data"=>I("post.pin_data")
				
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		$user = $this->user;
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::CHECK_PASS,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'order_id'=>$param['order_id'],
			'mid'=>$param['mid'],
			'pin_data'=>$param['pin_data'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		
		if($result->rc == "00") {
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	/**
	 *  用户绑定账户查询
	 */
	 public function searchCard(){
		$user = $this->user;
		
		$usercard = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if(!$usercard) $this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡","code"=>"162") );
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
    	$break_point = isset($_POST['break_point'])?$_POST['break_point']:null;
    	
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::SEARCH_CARD,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace),
			'break_point'=>$break_point
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result,true);
		$cardinfo = array();
		$cardinfo = $result['relation_acc'];
		if($result['rc'] == "00") {
			$this->_returnJson(array("result"=>1,"relation_acc"=>$cardinfo,"rc"=>$result['rc'],"info"=>$result['rc_detail'],"memo"=>$result['memo']));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result['rc_detail'],"rc"=>$result['rc'],"memo"=>$result['memo']));
		}
    }
	
	/**
	 *  用户默认核销账户（卡号）选择
	 */
	 public function setCard(){
		$user = $this->user;
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		$param=array(
    			"pan"=>I("post.pan")
    	);
		if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::SET_CARD,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'pan'=>$param['pan'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		if($result->rc == "00") {
			$userCards = M("UserCard")->where(array('userID'=>$user['uid'],'oldornew'=>1))->select();
			foreach($userCards AS $key=>$value){
				$usercarddata['cardID']=$value['cardID'];
				$usercarddata['is_default']=0;
				M("UserCard")->save($usercarddata);
			}
			$userCard = M("UserCard")->where(array('userID'=>$user['uid'],'cardNum'=>$param['pan'],'oldornew'=>1))->find();
			D("UserCard")->updateCardNew($userCard['cardID'],$user['uid'],$param['pan']);
			
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
    }
	
	/**
	 *  获取订单列表
	 */
	 public function searchOrder(){
		$user = $this->user;
		
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if((!$usermodel['realname']) || (!$usermodel['realname'] && !$usercardmodel)){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证、绑定汇通卡才能使用本功能！","code"=>"168") );
		}                             //实名认证开放
		if(!$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡才能使用本功能！","code"=>"169") );
		}
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		$break_point = isset($_POST['break_point'])?$_POST['break_point']:null;
		//if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::SEARCH_ORDER,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace),
			'break_point'=>$break_point
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		//do{
			$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
			//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
			//test
			//$result = json_decode($result,true);
			//$this->_returnJson(array("result"=>1,"info"=>$result,"rc"=>$result['rc'],"memo"=>$result['memo']));
			//test
			if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
			
			$result = json_decode($result,true);
			$orderinfo = $result['order_info'];
			if($result['rc']){
				if($result['rc'] == "00") {
					$this->_returnJson(array("result"=>1,"info"=>$result['rc_detail'],"rc"=>$result['rc'],"orderinfo"=>$orderinfo,"memo"=>$result['memo']));
				}else{
					$this->_returnJson(array("result"=>0,"info"=>$result['rc_detail'],"rc"=>$result['rc'],"memo"=>$result['memo']));
				}
			}
		//}while($result['rc']);
		
    }
	
	
	
	/**
	 *  实名认证
	 */
	 public function realnameVertify(){
		$user = $this->user;
		
		$param=array(
    			"cardno"=>I("post.cardno"),
				"username"=>urldecode($_POST['username']),
				"certtype"=>I("post.certtype"),
				"certno"=>I("post.certno"),
				"bankcode"=>I("post.bankcode"),
				"cardphone"=>I("post.cardphone")
    	);
		
		//file_put_contents("payLog/shiming_".date("Ymd").".txt", json_encode(json_encode($param)."-----------------------",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		/*$param=array(
    			"cardno"=>"6660718400000000125",
				"username"=>"周靖翀",
				"certtype"=>"0",
				"certno"=>"44082319850613007X",
				"bankcode"=>"102",
				"cardphone"=>"18664699093"
    	);*/
		//if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		$reqno = time().rand(0,999999);
		$msg = $param['cardno']."|".$param['username']."|".$param['certtype']."|".$param['certno']."|".$param['cardphone'];
		//file_put_contents("payLog/shiming_".date("Ymd").".txt", json_encode($msg."-----------------------",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		
		$msg = urlencode($msg);
		$bContent = str_split($msg, 1);
		$bKey = str_split(C("SHIMING_PWD"), 1);
		
		for ($i = 0; $i < count($bContent); $i++) {
			foreach($bKey as $key=>$temp) {
				$bContent[$i] = $bContent[$i] ^ $temp;
			}
		}
		$msg = join('', $bContent);
		$msg = urlencode($msg);
		
		//file_put_contents("payLog/shiming_".date("Ymd").".txt", json_encode($msg."-----------------------",JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);	
		$sign = $reqno.$param['cardno'].$param['username'].$param['certtype'].$param['certno'].$param['bankcode'].$param['cardphone'];
		$sign = $this->_getSignPKCS12($sign);
		$sign = urlencode($sign);
		
		$postparam = array(
			"REQ_SN"=>$reqno,
			"PROVINCE"=>'',
			"CITY"=>'',
			"BANK_NAME"=>'',
			"BANK_CODE"=>$param['bankcode'],
			"VERIFY_MSG"=>$msg,
			"NOTICE_URL"=>C('SERVER_DOMAIN')."/Api/CodePay/getShiming.html",
			"partnerCode"=>C('SHIMING_CODE'),
			"SIGN_MSG"=>$sign
		);
		$msg = urlencode($msg);
		$result=http_post(C('SHIMING_URL')."REQ_SN=".$reqno."&PROVINCE="."&CITY="."&BANK_NAME="."&BANK_CODE=".$param['bankcode']."&VERIFY_MSG=".$msg."&NOTICE_URL=".C('SERVER_DOMAIN')."/Api/CodePay/getShiming.html"."&partnerCode=".C('SHIMING_CODE')."&SIGN_MSG=".$sign,"");
    	//$result=http_post_shiming(C('SHIMING_URL'),$postparam);
		//$result=http_post_shiming("http://172.16.111.234:8081/Paygateway/payment/agentVerify.do",$postparam);
		//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		S(C("CACHE_MEM"));
		S('shiming_card_'.$param['cardno'],$user['uid']);
		S('shiming_'.$user['uid'],$param['cardno']."|".$param['username']."|".$param['certtype']."|".$param['certno']."|".$param['cardphone']."|".$param['bankcode']);
		$this->_returnJson(array("result"=>1,"info"=>"实名认证请求发送成功"));
    }
	
	public function getShiming(){
		
		$postStr = $_GET['test'];
		file_put_contents("payLog/shiming_".date("Ymd").".txt", $postStr.PHP_EOL,FILE_APPEND);
		//file_put_contents("payLog/pushlog_20160330.txt", $postStr.PHP_EOL,FILE_APPEND);
		echo $postStr;
		exit;
		
		//$postStr = file_get_contents("php://input");
		//file_put_contents("payLog/shiming_".date("Ymd").".txt", json_encode($postStr,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
		$postStr = $_POST['VERIFY_RESP_MSG'];
		$content = str_replace("%(?![0-9a-fA-F]{2})", "%25",$postStr); 
		$content = urldecode($content);
		$bContent = str_split($content, 1);
		$bKey = str_split(C("SHIMING_PWD"), 1);
		for ($i = 0; $i < count($bContent); $i++) {
			foreach($bKey as $key=>$temp) {
				$bContent[$i] = $bContent[$i] ^ $temp;
			}
		}
		$result = join('', $bContent);
		$result = urldecode($result);
		
		$result = explode('|',$result);
		S(C("CACHE_MEM"));
		$userID = S('shiming_card_'.$result[0]);
		$data = S('shiming_'.$userID);
		$data = explode('|',$data);
		$user = M('User')->where(array('userID'=>$userID))->find();
		if($result[1]=="0000"){
			$userdata = array(
				'userID'=>$userID,
				'realname'=>$data[1],
				'idno'=>$data[3]
			);
			M('User')->save($userdata);
			$userbank = array(
				'userID'=>$userID,
				'cardnum'=>$result[0],
				'bankno'=>$data[5],
				'cardphone'=>$data[4]
			);
			M('UserBank')->add($userbank);
			$msgarray = array('type'=>'realnameVertify','result'=>1,'info'=>'实名认证成功');
			$msg = json_encode($msgarray);
			$title = "实名认证校验";
			 vendor('JPush/autoload');//JPushClient   notification  APIRequestException APIConnectionException
			//$client = new JPushClient('0335dd3eb505909bdc492d06', 'f9f8e4b165b9448fc0fd0539');   //测试key
			  $client = new JPushClient('161f1017deaf5dc1cba3e83d', 'bb3a91fe849af6cb1d754db9');   //生产key
			try {
					$result = $client->push()
						->setPlatform( M\all )
						//->setAudience( M\all)
						->setAudience(M\audience(M\alias(array($user['accessToken']))))
						//->setNotification( 
						//    M\notification($msg, 
						//    M\ios($title, null, null, null, $msgarray, null),
						//    M\android($title, null, null, $msgarray)
						//))
						->setMessage(M\message($msg, $title, 'array', $msgarray))
						//->printJSON()
						->send();
				
				
						
				return $result;
			} catch (APIRequestException $e) {
				
				return false;
			} catch (APIConnectionException $e) {
				
				return false;
			}
		} else{
			$msgarray = array('type'=>'realnameVertify','result'=>0,'info'=>$result[2],'code'=>$result[1]);
			$msg = json_encode($msgarray);
			$title = "实名认证校验";
			 vendor('JPush/autoload');//JPushClient   notification  APIRequestException APIConnectionException
			//$client = new JPushClient('0335dd3eb505909bdc492d06', 'f9f8e4b165b9448fc0fd0539');   //测试key
			  $client = new JPushClient('161f1017deaf5dc1cba3e83d', 'bb3a91fe849af6cb1d754db9');   //生产key
			try {
					$result = $client->push()
						->setPlatform( M\all )
						//->setAudience( M\all)
						->setAudience(M\audience(M\alias(array($user['accessToken']))))
						//->setNotification( 
						//    M\notification($msg, 
						//    M\ios($title, null, null, null, $msgarray, null),
						//    M\android($title, null, null, $msgarray)
						//))
						->setMessage(M\message($msg, $title, 'array', $msgarray))
						//->printJSON()
						->send();
				
				
						
				return $result;
			} catch (APIRequestException $e) {
				
				return false;
			} catch (APIConnectionException $e) {
				
				return false;
			}
		}
		
		
		
	}
	
	public function checkRealname(){
		$user = $this->user;
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		if($usermodel['realname']){
			$userbank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			$this->_returnJson(array("result"=>1,"info"=>'',code=>"171","userinfo"=>array('username'=>urldecode($usermodel['realname']),'certno'=>$usermodel['idno'],'bankcode'=>$userbank['bankno'],'cardno'=>$userbank['cardnum'],'cardphone'=>$userbank['cardphone'])));
		}else{
			$this->_returnJson(array("result"=>1,"info"=>'尚未实名认证',code=>"170"));
		}
	}
	
	public function sendSms(){
		$user = $this->user;
		
		$type = $_POST['type'];
		if($type==318){
			$mobile = $_POST['mobile'];
		}else{
			$user_bank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			if($user_bank){
				$mobile = $user_bank['cardphone'];
			}
		}
		/*if($_POST['mobile']){
			$mobile = $_POST['mobile'];
		}else{
			$user_bank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			if($user_bank){
				$mobile = $user_bank['cardphone'];
			}
		}*/
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::GET_PHONECODE,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace),
			'mobile'=>$mobile,
			'req_txn_id'=>$type
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		if($result->rc == "00") {
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
	}
	
	public function checkSms(){
		$user = $this->user;
		
		
		if($_POST['mobile']){
			$mobile = $_POST['mobile'];
		}else{
			$user_bank = M('UserBank')->where(array('userID'=>$user['uid']))->find();
			if($user_bank){
				$mobile = $user_bank['cardphone'];
			}else{
				$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
			}
		}
		if(!$_POST['verify_code'])$this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::CHECK_PHONECODE,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'systrace'=>sprintf("%06d", $systrace),
			'mobile'=>$mobile,
			'verify_code'=>$_POST['verify_code']
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		if($result->rc == "00") {
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
	}
	
	public function checkAll(){
		$user = $this->user;
		$usermodel = M('User')->where(array('userID'=>$user['uid']))->find();
		$usercardmodel = M('UserCard')->where(array('userID'=>$user['uid'],'isOn'=>1,'oldornew'=>1))->find();
		if((!$usermodel['realname']) || (!$usermodel['realname'] && !$usercardmodel)){
			$this->_returnJson(array("result"=>0,"info"=>"请先进行实名认证、绑定汇通卡才能使用本功能！","code"=>"168") );
		}                             //实名认证开放
		if(!$usercardmodel){
			$this->_returnJson(array("result"=>0,"info"=>"请先绑定汇通卡才能使用本功能！","code"=>"169") );
		}
		$this->_returnJson(array("result"=>1,"info"=>"已经实名认证和绑卡！","code"=>"173") );
	}
	
	public function checkOtherpass(){
		$param=array(
				"pin_data"=>I("post.pin_data")
    	);
    	if(!isNotEmptyArr($param)) $this->_returnJson(array("result"=>0,"info"=>"missing parameter","code"=>"123"));
		$user = $this->user;
		
		//$user['uid'] = 5417;
		//$user['mobileNum'] = '18664699093';
		
		S(C("CACHE_MEM"));
		if(!S('systrace_'.$user['uid'].'_'. date("Ymd"))){
			$systrace = 0;
		}else{
			$systrace = S('systrace_'.$user['uid'].'_'. date("Ymd"));
		}
		if($systrace>999999){
			$this->_returnJson(array("result"=>0,"info"=>'超过最大扫码次数'));
		}
		$systrace = $systrace+1;
		$data=array(
    		'txn_id'=>self::CHECK_OTHERPASS,
    		'channel'=>self::CHANNEL,
			'chan_user'=>(string)($user['mobileNum']),
			'pin_data'=>$param['pin_data'],
			'systrace'=>sprintf("%06d", $systrace)
		);

		S('systrace_'.$user['uid'].'_'. date("Ymd"),$systrace,60*60*24);
		$data = $this->getdata($data);
		
		$result=socket_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT_TEST'),$data);
    	//$result=socket_security_post(C('CODE_PAY_URL'),C('CODE_PAY_PORT'),$data);
		
		if (!$result) $this->_returnJson(array("result"=>0,"info"=>"api return error","errorMsg"=>'接口错误',"code"=>"119") );
		
		$result = json_decode($result);
		
		if($result->rc == "00") {
			$this->_returnJson(array("result"=>1,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}else{
			$this->_returnJson(array("result"=>0,"info"=>$result->rc_detail,"rc"=>$result->rc,"memo"=>$result->memo));
		}
	}
	
	private function getdata($data){
		$sign = "";
		ksort($data);
		foreach($data AS $key=>$value){
			if($value==end($data)){
				$sign .= $key . "=" . $value;
			} else {
				$sign .= $key . "=" . $value . "&";
			}
		}
		$sign = strtoupper(md5($sign));
		$signdata = array('sign'=>$sign);
		
		$data = json_encode(array_merge($data,$signdata));
		return $data;
	}
	
	private function _getSignPKCS12($msg)
	{
		$pfx = './cert/'.C("SHIMING_PFX");
		$pwd = C("SHIMING_PWD");
		return $this->_signByPkcs12($msg,$pfx,$pwd);
	}
    
    private function _signByPkcs12($msg,$pfx,$pwd='')
	{
		$key=array();
		openssl_pkcs12_read(file_get_contents($pfx),$key,$pwd);
		openssl_sign($msg, $sign, $key['pkey']);
		return base64_encode($sign);
	}
    
}